import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
// 更新存储的数据
var car = JSON.parse(localStorage.getItem('car') || '[]')
export default new Vuex.Store({
  state: {
    car: car
  },
  mutations: {
    addTo(state, goodsinfo) {
      var flag = false
      state.car.some(item => {
        if (item.id === goodsinfo.id) {
          item.cound += parseInt(goodsinfo.cound)
          flag = true
          return true
        }
      })
      if (!flag) {
        state.car.push(goodsinfo)
      }
      // 当更新car之后吧car数组存储到本地的页面
      localStorage.setItem('car', JSON.stringify(state.car))
    },
    upcart(state, goods) {
      // 控制购物车中商品数量
      state.car.some(item => {
        if (item.id === goods.id) {
          item.cound = parseInt(goods.cound)
          return true
        }
      })
      // 把最新的结果放到页面中
      localStorage.setItem('car', JSON.stringify(state.car))
    },
    removeCart(state, id) {
      // 删除购物车数据
      state.car.some((item, i) => {
        if (item.id === id) {
          state.car.splice(i, 1)
          return true
        }
      })
      localStorage.setItem('car', JSON.stringify(state.car))
    },
    upselected(state, info) {
      // 控制开关数据
      state.car.some(item => {
        if (item.id === info.id) {
          item.selected = info.selected
          return true
        }
      })
      localStorage.setItem('car', JSON.stringify(state.car))
    }
  },
  // 计算属性
  getters: {
    // 购物车数量
    getAll(state) {
      var c = 0
      state.car.forEach(item => {
        c += item.cound
      })
      return c
    },
    getgood(state) {
      var o = {}
      state.car.forEach(item => {
        o[item.id] = item.cound
      })
      return o
    },
    getXuanz(state) {
      var l = {}
      state.car.forEach(item => {
        l[item.id] = item.selected
      })
      return l
    },
    getJiag(state) {
      var c = {
        count: 0,
        amount: 0
      }
      state.car.forEach(item => {
        if (item.selected) {
          c.count += item.cound
          c.amount += parseInt(item.price * item.cound)
        }
      })
      return c
    }
  },
  actions: {}
})
